package com.heye.imheye.controller;

import com.heye.imheye.dto.ChatroomCreateReq;
import com.heye.imheye.dto.ChatroomDeleteReq;
import com.heye.imheye.dto.ChatroomInfoReq;
import com.heye.imheye.dto.ChatroomMessagesReq;
import com.heye.imheye.entity.Chatroom;
import com.heye.imheye.entity.Message;
import com.heye.imheye.entity.QMessage;
import com.heye.imheye.repository.ChatroomRepository;
import com.heye.imheye.repository.MessageRepository;
import com.heye.imheye.server.Server;
import com.heye.imheye.util.ContextUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chatroom")
@RequiredArgsConstructor
public class ChatroomController {

    private final Server server;
    private final ChatroomRepository chatroomRepository;
    private final MessageRepository messageRepository;

    @PostMapping("/create")
    public void create(@RequestBody ChatroomCreateReq req) {
        Chatroom chatroom = new Chatroom();
        chatroom.setName(req.name());
        chatroomRepository.save(chatroom);
    }

    @PostMapping("/delete")
    public void delete(@RequestBody ChatroomDeleteReq req) {
        chatroomRepository.deleteById(req.id());
    }

    @GetMapping("/list")
    public Page<Chatroom> list(@PageableDefault Pageable pageable) {
        return chatroomRepository.findAll(pageable);
    }

    @GetMapping("/info")
    public Chatroom info(ChatroomInfoReq req) {
        Chatroom chatroom = chatroomRepository.findById(req.id()).orElseThrow();
        server.addChatroomMember(chatroom.getId(), ContextUtil.getUserId());
        return chatroom;
    }

    @GetMapping("/messages")
    public List<Message> messages(ChatroomMessagesReq req, @PageableDefault Pageable pageable) {
        QMessage message = QMessage.message;
        QPageRequest pageRequest = QPageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), message.createTime.desc());

        messageRepository.findAll(message
                .toId.eq(req.toId())
                .and(message.toType.eq(req.toType())), pageRequest);
        return null;
    }
}
